package com.gxatek.cockpit.dvr.service;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.gxatek.cockpit.dvr.service.view.CustomLineChart;
import com.gxatek.cockpit.dvr.service.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用MPAndroidChart显示加速度的数据，数据是之前在androidStudio里输出的，copy到了文件里，然后读取文件，显示x,y,z的值
 *
 */
public class MainActivity extends AppCompatActivity implements SensorEventListener {
    private SensorManager sensorManager;
    private Sensor accelerometer;
    String TAG = "MainActivity";

    List<Item> list = new ArrayList<>();
    List<Float>dataList = new ArrayList<>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    CustomLineChart markerView;
    TextView tvResult;

    public static int MSG_LOAD_DATA_FINISHED = 10;
    Handler handler = new Handler(Looper.getMainLooper()) {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_LOAD_DATA_FINISHED) {
                Log.e(TAG, "数据解析完：list.size=" + list.size());
                for (int i = 0; i < list.size(); i++) {
                    Log.e(TAG, "x=" + list.get(i).values[0] + " y=" + list.get(i).values[1] + " z=" + list.get(i).values[2]);
                }
                dataList.clear();
                for(int i=0;i<list.size();i++){
                    dataList.add(list.get(i).values[0]);
                }
                markerView.setData(dataList);
                markerView.invalidate();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkCallingPermission(Manifest.permission.BODY_SENSORS) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.BODY_SENSORS}, 10);
            }
        }
        tvResult = findViewById(R.id.tvClickResult);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        markerView = findViewById(R.id.markerView);
        markerView.setLineColor(Color.BLACK);
        markerView.setPointColor(Color.RED);
        markerView.setPointSize(1);

        new Thread(){
            @Override
            public void run() {
                super.run();
                Log.e(TAG, "run--->");

                BufferedReader br = null;
                try {
                    br = new BufferedReader(new InputStreamReader(getAssets().open("data.txt")));
                    String line  = null;
                    while( (line = br.readLine())!=null ){
                        String arr[] = line.split("x=");
                        Date date = sdf.parse(arr[0].trim());
                        String first[] = arr[1].split("y=");
                        float x = Float.parseFloat(first[0].trim());
                        String second[] = first[1].split("z=");
                        float y = Float.parseFloat(second[0].trim());
                        float z = Float.parseFloat(second[1].trim());
                        list.add(new Item(new float[]{x,y,z}, date));
                    }
                    Log.e(TAG, "数据加载完成");
                    handler.sendEmptyMessage(MSG_LOAD_DATA_FINISHED);
                } catch (IOException | ParseException e) {
                    e.printStackTrace();
                    Log.e(TAG, e.getMessage());
                }finally {
                    if(br!=null){
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }.start();


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e(TAG, "onRequestPermissionsResult->permissions.length=" + permissions.length + " granted.length=" + grantResults.length);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //第三个参数表示延时多久发一次
        /**
         * SENSOR_DELAY_FASTEST 最低延迟 0us，一般不推荐使用，该种模式可能造成手机电力大量消耗，会影响手机性能
         * SENSOR_DELAY_GAME 游戏延迟 20,000 us，一般绝大多数的实时性较高的游戏都使用该级别
         * SENSOR_DELAY_UI 界面延迟 60,000 us ，一般对于屏幕方向自动旋转使用，相对节省电能和逻辑处理，一般游戏开发中我们不使用。
         * SENSOR_DELAY_NORMAL 标准延迟 200,000 us，200ms ，对于一般的简单小游戏可以使用，但过低的采样率可能对一些赛车类游戏有跳帧现象。
         */
        sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}